// pages/myAdviser/myAdviser.js
/**修改1.去除授权页面，留loading
   2.主管信息通过接口获取，不需要通过option 获取
*/

var common = require("../../utils/common.js");
//index.js
//获取应用实例
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    options: [],
    canIUse: false,
    loading: true,
    zuGInfo:'',//主管信息
    listHeight:'',
    isMore:false,
    isInf:"查看详情",
    isShowImg:false,
    bannerList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options);
    console.log(app);
    that.setData({
       zuGInfo:options
     })
    // if (options.xcxid) {
    //   that.setData({
    //     xcxid: options.xcxid
    //   })
    // }

    if (app.globalData.xcxtype.hasLogo == '1') {
      //显示水印
      this.setData({
        hasWaterLogo: true
      })
    } else {
      this.setData({
        hasWaterLogo: false
      })
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setNavigationBarTitle({
      title: '顾问详情'
    });
    var that = this;
    // wx.login({
    //   success: res => {
    //     if (res.code) {
    //       var code = res.code;
    //       //获取xcxOpenId;
    //       // 获取用户信息
    //       wx.getSetting({
    //         success: res => {
    //           if (res.authSetting['scope.userInfo']) {
    //             wx.getUserInfo({
    //               success: function (res) {
    //                 app.globalData.userInfoMine = res.userInfo;
    //                 app.globalData.isFind = true;
    //                 that.getOpenId(code);
    //               }
    //             })
    //           } else {
    //             //未授权登录
    //             app.globalData.isFind = false;
    //             that.getOpenId(code);
    //             that.setData({
    //               loading: false,
    //               canIUse: true
    //             })
    //           }
    //         }
    //       })
    //     } else {
    //       console.log(3);
    //       console.log('登录失败！' + res.errMsg);
    //       that.setData({
    //         loading: true
    //       })
    //     }
    //   }
    // })
  
    // that.getHouseInfo();
    that.modifyOnlookers();
    that.getUser();
  },
  
  // getHouseInfo:function(){
  //   //获取房屋信息
  //   var that = this;
  //   common.ajaxPost(
  //     'portal/wlpBuilding/queryBuilding.action', {
  //       id: app.globalData.lpid
  //     },
  //     function (res) {
  //       console.log(res)
  //       if (res && res.length > 0) {
  //         var data = res[0];
  //         console.log(data);
  //         var houseName=data.name;
  //         var houseLable = data.houseLable;
  //         var houseTips = data.houseLable.split("|");
  //         var houseAvgPrice = data.avgPrice;
  //         var housePhone = data.phone;
  //         var banner = data.banners.split(";");
  //         that.setData({
  //           houseName: houseName,
  //           houseLable: houseLable,
  //           houseTips: houseTips,
  //           houseAvgPrice : houseAvgPrice,
  //           housePhone: housePhone,
  //           bannerList: banner
  //         })
  //       }
  //     }
  //   ) 
  // },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.isShareBack = true;
    app.globalData.isGoBack = true; 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享,
   * 改版分享用户必须的数据 即bid(楼盘id)和id(顾问id),isIndex用来走index页面时不播放视频，图片等
   * 
   */
  onShareAppMessage: function () {
    var that = this;
    var guwenId;
    if (that.data.zuGInfo.id){
      //正常流程进入
      guwenId = that.data.zuGInfo.id;
    }

    //  console.log('/pages/index/index?type=myAdviser&headimage=' + that.data.zuGInfo.headimage + ' &name=' + that.data.zuGInfo.name + '&id=' + that.data.zuGInfo.id + ' &usertype=' + that.data.zuGInfo.usertype + '&hasNoReceive=' + that.data.zuGInfo.hasNoReceive + '&position=' + that.data.zuGInfo.position + '&weixin=' + that.data.zuGInfo.weixin + '&weixinQrcode=' + that.data.zuGInfo.weixinQrcode + '&phone=' + that.data.zuGInfo.phone + '&bid=' + app.globalData.bid + "&isIndex=1");
    // var xcxids;
    // if (app.globalData.xcxshareid) {
    //   xcxids = app.globalData.xcxshareid
    // } else {
    //   xcxids = app.globalData.queryWlpXcxByParams[0].id
    // }
    var bid;
    if (app.globalData.shareBid) {
      bid = app.globalData.shareBid;
    } else {
      bid = app.globalData.bid
    }
    return {
      title:app.globalData.myAdviser.name,
      path: '/pages/index/index?type=myAdviser&id=' + guwenId + '&bid=' + bid + "&isIndex=1",
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**拨打电话 */
  call:function(e){
    var phone=e.currentTarget.id;
    wx.makePhoneCall({
      phoneNumber: phone  //仅为示例，并非真实的电话号码
    })
  },
  
  //添加到通讯录
  addContact:function(e){
    console.log(e);
    console.log(e.currentTarget.dataset.photofilepath);
    wx.addPhoneContact({
      photoFilePath: e.currentTarget.dataset.photofilepath,
      // mobilePhoneNumber: e.currentTarget.dataset.mobilePhoneNumber,
      remark: e.currentTarget.dataset.remark,
      mobilePhoneNumber: e.currentTarget.dataset.mobilephonenumber,
      firstName: e.currentTarget.dataset.firstname,
      weChatNumber: e.currentTarget.dataset.wechatnumber,
      success:function(){
        console.log("success")
      }
    })
  },

  //跳转
  gotoDetail:function(){
    wx.switchTab({
      url: '../detail/detail',
    })
  },

  // gotoerweima:function(){
  //   var that=this;
  //   wx.navigateTo({
  //     url: '../adviserDetail/adviserDetail?headimage='+that.data.zuGInfo.headimage+'&name=' +that.data.zuGInfo.name+'&id='+ that.data.zuGInfo.id+'&usertype='+ that.data.zuGInfo.usertype + '&hasNoReceive=' + that.data.zuGInfo.hasNoReceive + '&position=' + that.data.zuGInfo.position + '&weixin=' + that.data.zuGInfo.weixin + '&weixinQrcode=' + that.data.zuGInfo.weixinQrcode + '&phone=' + that.data.zuGInfo.phone + '&bid=' + app.globalData.bid + "&isIndex=1",
  //   })
  // },

  copy: function (e) {
    var that = this;
    var weixin=e.currentTarget.dataset.weixin;
    wx.setClipboardData({
      data: weixin,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },

  calls:function(e){
     //判断权限，若是体验版，无跳转
     console.log(app)
    if(app.globalData.xcxtype.consType=="0"){
      return false
    }
    var that=this;
    var headimage = that.data.zuGInfo.headImage;
    var name = that.data.zuGInfo.name
    var id = that.data.zuGInfo.id
    var usertype = that.data.zuGInfo.userType
    console.log(headimage + '.....' + name + '........' + id + '.........' + usertype);
    //判断是否授权，没有跳转list
    wx.navigateTo({
      url: '../rooms/rooms?headimage=' + headimage + '&name=' + name + '&id=' + id + '&usertype=' + usertype,
    })
  },

  //  getOpenId: function (code) {
  //   var that = this;
  //    var xcxid;
  //    if (that.data.xcxid) {
  //      xcxid = that.data.xcxid
  //    } else if (app.globalData.xcxshareid) {
  //      xcxid = app.globalData.xcxshareid
  //    } else {
  //      xcxid = app.globalData.queryWlpXcxByParams[0].id
  //    }
  //   common.ajaxPost(
  //     'portal/wlpUsers/getXcxOpenId.action', {
  //       code: code,
  //       xcxId: xcxid
  //     },
  //     function (res) {
  //       if (res && res["result"]) {
  //         console.log(res);
  //         app.globalData.xcxOpenId = res.xcxOpenId;
  //         // that.findUser();
  //         if (app.globalData.isFind) {
  //           //已授权
  //           that.findUser();
  //         } else {
  //           //未授权
  //         }
  //       }
  //     }
  //   )
  // },

  //  openSetting: function (e) {
  //    console.log(e);
  //    var that = this;
  //    if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
  //      return false;
  //    } else {
  //      console.log(e.detail.userInfo);
  //      app.globalData.userInfoMine = e.detail.userInfo;
  //      //授权时查询用户
  //      that.setData({
  //        canIUse: false,
  //        loading: true
  //      });
  //      that.findUser();
  //    }
  //  },

  //  findUser: function () {
  //    var that = this;
  //    console.log(app.globalData.xcxOpenId);
  //    //查询用户是否存在
  //    common.ajaxPostNo(
  //      'portal/wlpUsers/queryUserInfo.action', {
  //        xcxOpenId: app.globalData.xcxOpenId,
  //        bid: app.globalData.bid,
  //        userType: 2
  //      },
  //      function (res) {
  //        if (res.data.resultCode == "1000") {
  //          app.globalData.userInfoMine = res.data.userInfo;
  //          that.setData({
  //            loading: false,
  //            canIUse: false
  //          })
  //        } else {
  //          //用户不存在
  //          that.modifyUser();
  //        }
  //        return false;
  //      }
  //    )
  //  },

   gotoAuthentication() {
     this.queryHasAuth();
     // wx.navigateTo({
     //   url: '../tmList/tmList',
     // })
     //到专属顾问认证

   },

   queryHasAuth: function () {
     //查询是否认证过了，认证过了跳转tmlist,否则认证
     var that = this;
     common.ajaxPost(
       'portal/wlpUsers/queryHasAuth.action', {
         xcxOpenId: app.globalData.xcxOpenId,
         bid: app.globalData.bid
       },
       function (res) {
         if (res && res["result"]) {
           if (res.resultMsg == "未认证!") {
             app.globalData.isAuto = false;
             wx.navigateTo({
               url: '../authentication/authentication',
             })
           } else {
             //存储顾问信息
             console.log(res);
             var GwHeadImage = res.GwHeadImage;
             var GwName = res.GwName;
             var GwUserType = res.GwUserType;
             var Gwid = res.Gwid;
             var bid = app.globalData.bid;
             wx.navigateTo({
               url: '../tmList/tmList?GwHeadImage=' + GwHeadImage + "&GwName=" + GwName + "&GwUserType=" + GwUserType + "&Gwid=" + Gwid + '&bid=' + bid,
             })
           }
         }
       }
     )
   },

  moreInf:function(){
      //更多
      var isInf=(this.data.isInf=="查看详情"?"收起详情":"查看详情");
      this.setData({
        isMore: !this.data.isMore,
        isInf: isInf
      })
  },
   getHeight:function(el,callback){
     //获取元素高度
     var that=this;
     var obj = wx.createSelectorQuery();
     obj.selectAll(el).boundingClientRect(function (rect) {
       console.log(rect[0].height)
       console.log(rect[0].width)
       that.setData({
         listHeight: rect[0].height
       })
        this.listTop = rect[0].top
        callback();
     })
     obj.exec();
   },
   modifyUser: function () {
     //保存用户信息
     var that = this;
     common.ajaxPost(
       'portal/wlpUsers/modifyUser.action', {
         userType: 2,
         headImage: app.globalData.userInfo.avatarUrl,
         name: app.globalData.userInfo.nickName,
         bid: app.globalData.bid,
         xcxOpenId: app.globalData.xcxOpenId,
       },
       function (res) {
         console.log(res);
         if (res && res["result"]) {
           if (res.resultMsg == '操作成功') {
             //添加成功，显示列表页
             that.setData({
               canIUse: false,
               loading: false
             });
             //that.getList();
           } else {
             //添加成功，显示列表页
             that.setData({
               canIUse: false,
               loading: true
             });
           }
         }
       }
     )
   },

  saveImg:function() {
    //根据接口获取图片
    var that=this;
    that.setData({
      isShowImg:true
    })
  },
  closeZZ:function(){
    var that = this;
    that.setData({
      isShowImg: false
    })
  },

 
  saveImgToPhotosAlbumTap:function(e) {
    var imgUrl = e.currentTarget.dataset.imgurl;
    let self = this
    // 相册授权
    wx.getSetting({
      success(res) {
        // 进行授权检测，未授权则进行弹层授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log("收全成功");
              self.saveImgs(imgUrl)
            },
            // 拒绝授权时，则进入手机设置页面，可进行授权设置
            fail() {
              wx.openSetting({
                success: function (data) {
                  console.log("openSetting success");
                  console.log("2");
                },
                fail: function (data) {
                  console.log(data);
                  console.log("openSetting fail");
                  self.setData({
                    canIUse: true,
                    loading: false,
                  })
                }
              });
            }
          })
        } else {
          // 已授权则直接进行保存图片
          self.saveImgs(imgUrl)
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  
  saveImgs: function (imgUrl){
    var imgurl=imgUrl;
    var that = this;
    wx.downloadFile({
      url: imgurl,
      success: function (res) {
        console.log(res);
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            console.log(data);
            wx.showToast({
              title: '图片保存成功',
              duration:1500,
              success:function(){
                setTimeout(function(){
                  that.closeZZ();
                },1500)
              }
            });
          },
          fail: function (err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("用户一开始拒绝了，我们想再次发起授权")
              console.log('打开设置窗口')
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              })
            }
          }
        })
      }
    })
  },

  getUser: function () {
    //获取用户信息
    var that = this;
    var bid;
    if(app.globalData.bid){
      bid = app.globalData.bid
    }else{
      bid = that.data.zuGInfo.bid
    }
    common.ajaxPost(
      'portal/wlpUsers/getuser.action', {
        id: that.data.zuGInfo.id,
        bid: bid ,
        toUserId:app.globalData.userInfo.id
      },
      function (res) {
        console.log(res);
        if (res && res["result"]) {
           that.setData({
             loading:false,
             zuGInfo: res.userInfo
           })
          var data = res.user;
          var houseName = data.name;
          var houseLable = data.houseLable;
          var houseTips = data.houseLable.split("|");
          var houseAvgPrice = data.avgPrice;
          var housePhone = data.phone;
          var banner = data.banners.split(";");
          that.setData({
            houseName: houseName,
            houseLable: houseLable,
            houseTips: houseTips,
            houseAvgPrice : houseAvgPrice,
            housePhone: housePhone,
            bannerList: banner
          })
        }
      }
    )
  },
  modifyOnlookers: function () {
    //添加围观人员
    var nikeName;
    var headImg;
    var that=this;
    if (app.globalData.alluserInfo) {
      nikeName = app.globalData.alluserInfo.nickName;
      headImg = app.globalData.alluserInfo.avatarUrl;
    } else {
      nikeName = app.globalData.userInfoweixin.nickName;
      headImg = app.globalData.userInfoweixin.avatarUrl;
    }
    common.ajaxPost(
      'portal/wlpgwOnlookers/modifygwOnlookers.action', {
        nikeName: nikeName,
        headImg: headImg,
        bid: app.globalData.bid,
        openId: app.globalData.xcxOpenId,
        gwid: that.data.zuGInfo.id
      },
      function (res) {
        if (res && res["result"]) {
          console.log(res);
        }
      }
    )
  },
})